import smtplib  # 导入smtplib库，用于发送邮件
from email.mime.text import MIMEText  # 导入MIMEText类，用于创建纯文本或HTML格式的邮件内容
from email.mime.multipart import MIMEMultipart  # 导入MIMEMultipart类，用于创建包含多个部分的邮件

class EmailSender:
    def __init__(self, smtp_server, smtp_port, sender_email, sender_password):
        # 初始化EmailSender类，设置SMTP服务器、端口、发件人邮箱和密码
        self.smtp_server = smtp_server  # SMTP服务器地址
        self.smtp_port = smtp_port  # SMTP服务器端口
        self.sender_email = sender_email  # 发件人邮箱地址
        self.sender_password = sender_password  # 发件人邮箱密码

    def send_email(self, receiver_email, subject, body, is_html=False):
        # 发送邮件方法，接收收件人邮箱、邮件主题、邮件内容和是否使用HTML格式的参数
        if is_html:
            # 如果邮件内容为HTML格式，创建MIMEText对象并指定格式为HTML
            msg = MIMEText(body, 'html')
        else:
            # 如果邮件内容为纯文本格式，创建MIMEText对象并指定格式为纯文本
            msg = MIMEText(body, 'plain')

        msg['Subject'] = subject  # 设置邮件主题
        msg['From'] = self.sender_email  # 设置发件人邮箱地址
        msg['To'] = receiver_email  # 设置收件人邮箱地址

        try:
            # 尝试连接SMTP服务器并发送邮件
            with smtplib.SMTP(self.smtp_server, self.smtp_port) as server:
                server.starttls()  # 启动TLS加密连接，确保通信安全
                server.login(self.sender_email, self.sender_password)  # 登录SMTP服务器
                server.sendmail(self.sender_email, receiver_email, msg.as_string())  # 发送邮件
            print("Email sent successfully!")  # 打印邮件发送成功的消息
        except Exception as e:
            # 如果发送邮件过程中发生异常，捕获并打印错误信息
            print(f"Failed to send email: {e}")

# Example usage:
#smtp.qq.com
email_sender = EmailSender('smtp.163.com', 25, 'testfan2@163.com', 'MSQOTDVQPMKSRZZS')
email_sender.send_email('279313259@qq.com', 'Subject Here', 'This is the body of the email.')
